<template>
  <div class="report-container">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="title">报表与统计</span>
          <div class="button-group">
            <el-button-group>
              <el-button 
                :type="currentChart === 'position' ? 'primary' : 'default'"
                @click="switchChart('position')"
                :class="{ active: currentChart === 'position' }"
              >
                岗位数量统计
              </el-button>
              <el-button 
                :type="currentChart === 'application' ? 'primary' : 'default'"
                @click="switchChart('application')"
                :class="{ active: currentChart === 'application' }"
              >
                岗位申请统计
              </el-button>
              <el-button
                  :type="currentChart === 'salary' ? 'primary' : 'default'"
                  @click="switchChart('salary')"
                  :class="{ active: currentChart === 'salary' }"
              >
                工资发放统计
              </el-button>
            </el-button-group>
            <div class="excel-buttons">
<!--              <el-upload-->
<!--                class="excel-upload"-->
<!--                action="#"-->
<!--                :auto-upload="false"-->
<!--                :show-file-list="false"-->
<!--                accept=".xlsx,.xls"-->
<!--                :on-change="handleFileChange"-->
<!--              >-->
<!--                <el-button type="primary">-->
<!--                  <el-icon><Upload /></el-icon>-->
<!--                  导入用户数据-->
<!--                </el-button>-->
<!--              </el-upload>-->
              <el-button type="success" @click="handleExport">
                <el-icon><Download /></el-icon>
                导出用户数据
              </el-button>
            </div>
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="chart-wrapper">
        <div v-show="currentChart === 'position'" v-loading="loading.positions" class="chart-container" ref="positionChartRef"></div>
        <div v-show="currentChart === 'application'" v-loading="loading.applications" class="chart-container" ref="applicationChartRef"></div>
        <div v-show="currentChart === 'salary'" v-loading="loading.salaries" class="chart-container" ref="salaryChartRef"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { getPositionStats, getApplicationStats } from "@/api/position.js"
import { getSalaryStats } from "@/api/salary.js"
import { exportUserExcel, importUserExcel } from "@/api/user.js"
import { ElMessage } from 'element-plus'
import { Refresh, Upload, Download } from '@element-plus/icons-vue'

const currentChart = ref('position')
const positionChartRef = ref(null)
const applicationChartRef = ref(null)
const salaryChartRef = ref(null)
let positionChart = null
let applicationChart = null
let salaryChart = null
const loading = ref({
  positions: false,
  applications: false,
  salaries: false
})

const chartOptions = {
  position: {
    title: {
      text: '岗位数量分布',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>数量: {c}个<br/>占比: {d}%'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'middle',
      type: 'scroll'
    },
    series: [
      {
        name: '岗位统计',
        type: 'pie',
        radius: ['45%', '75%'],
        center: ['45%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}个',
          textStyle: {
            fontSize: 14
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: []
      }
    ]
  },
  application: {
    title: {
      text: '岗位申请情况',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>申请数: {c}个<br/>占比: {d}%'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'middle',
      type: 'scroll'
    },
    series: [
      {
        name: '申请统计',
        type: 'pie',
        radius: ['45%', '75%'],
        center: ['45%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}个',
          textStyle: {
            fontSize: 14
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: []
      }
    ]
  },
  salary: {
    title: {
      text: '工资发放分布',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = params[0].name + '<br/>';
        params.forEach(param => {
          result += param.seriesName + ': ' + param.value + '元<br/>';
        });
        return result;
      }
    },
    legend: {
      data: ['总工资', '已发放'],
      top: 60
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 100,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        interval: 0,
        rotate: 30,
        margin: 35,
        formatter: function(value) {
          return value.length > 7 ? value.slice(0, 7) + '\n' + value.slice(7) : value;
        },
        align: 'center'
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '金额（元）',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: '总工资',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '已发放',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
}

const initChart = (type) => {
  let chart, chartRef;
  if (type === 'position') {
    chart = positionChart;
    chartRef = positionChartRef.value;
  } else if (type === 'application') {
    chart = applicationChart;
    chartRef = applicationChartRef.value;
  } else {
    chart = salaryChart;
    chartRef = salaryChartRef.value;
  }
  
  if (chart) {
    chart.dispose()
  }
  
  const newChart = echarts.init(chartRef)
  newChart.setOption(chartOptions[type])
  
  if (type === 'position') {
    positionChart = newChart
  } else if (type === 'application'){
    applicationChart = newChart
  } else {
    salaryChart = newChart
  }
  
  return newChart
}

const fetchData = async (type) => {
  const loadingKey = type === 'position' ? 'positions' : (type === 'application' ? 'applications' : 'salaries')
  loading.value[loadingKey] = true
  
  try {
    let api;
    if (type === 'position') api = getPositionStats;
    else if (type === 'application') api = getApplicationStats;
    else api = getSalaryStats;
    const res = await api()
    
    if (res.code === 0) {
      const data = res.data || []
      const typeName = type === 'position' ? '岗位' : (type === 'application' ? '申请' : '工资')
      if (data.length === 0) {
        ElMessage.warning(`暂无${typeName}数据`)
      }
      
      let chart;
      if (type === 'position') chart = positionChart;
      else if (type === 'application') chart = applicationChart;
      else chart = salaryChart;
      
      if (type === 'salary') {
        const processedData = data.map(item => ({
          name: item.name || '其他',
          totalSalary: parseFloat(item.totalSalary || 0).toFixed(2),
          paidSalary: parseFloat(item.paidSalary || 0).toFixed(2)
        }));

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              let result = params[0].name + '<br/>';
              params.forEach(param => {
                result += param.seriesName + ': ' + param.value + '元<br/>';
              });
              return result;
            }
          },
          legend: {
            data: ['总工资', '已发放'],
            top: 60
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: 100,
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: processedData.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30,
              margin: 35,
              formatter: function(value) {
                return value.length > 7 ? value.slice(0, 7) + '\n' + value.slice(7) : value;
              },
              align: 'center'
            },
            axisTick: {
              alignWithLabel: true
            }
          },
          yAxis: [{
            type: 'value',
            name: '金额（元）',
            axisLabel: {
              formatter: '{value}'
            }
          }],
          series: [
            {
              name: '总工资',
              type: 'bar',
              data: processedData.map(item => Number(item.totalSalary)),
              itemStyle: {
                color: '#409EFF'
              }
            },
            {
              name: '已发放',
              type: 'bar',
              data: processedData.map(item => Number(item.paidSalary)),
              itemStyle: {
                color: '#67C23A'
              }
            }
          ]
        };

        chart.setOption(option, true);
      } else {
        const processedData = data
          .map(item => ({
            name: item.name || '其他',
            value: Number(item.value) || 0
          }))
          .filter(item => type === 'position' || type === 'application' || item.value > 0)
        
        chart.setOption({
          series: [{
            data: processedData
          }]
        })
      }
    } else {
      const typeName = type === 'position' ? '岗位' : (type === 'application' ? '申请' : '工资')
      ElMessage.error(res.msg || `获取${typeName}数据失败`)
    }
  } catch (err) {
    const typeName = type === 'position' ? '岗位' : (type === 'application' ? '申请' : '工资')
    console.error(`获取${typeName}数据失败:`, err)
    ElMessage.error(`获取${typeName}数据失败: ` + (err.message || '未知错误'))
  } finally {
    loading.value[loadingKey] = false
  }
}

const switchChart = async (type) => {
  currentChart.value = type
  await nextTick()
  
  if (type === 'position') {
    if (!positionChart) {
      initChart('position')
      fetchData('position')
    }
    positionChart.resize()
  } else if (type === 'application') {
    if (!applicationChart) {
      initChart('application')
      fetchData('application')
    }
    applicationChart.resize()
  } else {
    if (!salaryChart) {
      initChart('salary')
      fetchData('salary')
    }
    salaryChart.resize()
  }
}

const refreshData = () => {
  if (currentChart.value === 'position') {
    fetchData('position')
  } else if (currentChart.value === 'application') {
    fetchData('application')
  } else {
    fetchData('salary')
  }
}

const resizeObserver = new ResizeObserver(() => {
  if (positionChart) positionChart.resize()
  if (applicationChart) applicationChart.resize()
  if (salaryChart) salaryChart.resize()
})

// Excel导入导出功能
const handleFileChange = async (file) => {
  try {
    const response = await importUserExcel(file.raw)
    ElMessage.success('用户数据导入成功')
  } catch (error) {
    ElMessage.error('用户数据导入失败：' + error.message)
  }
}

const handleExport = async () => {
  try {
    const response = await exportUserExcel()
    // 从响应头中获取文件名
    const contentDisposition = response.headers['content-disposition']
    let filename = '用户数据.xlsx'
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename=(.*\.xlsx)/)
      if (filenameMatch) {
        filename = decodeURIComponent(filenameMatch[1])
      }
    }
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('用户数据导出成功')
  } catch (error) {
    console.error('导出错误:', error)
    ElMessage.error('用户数据导出失败：' + (error.message || '未知错误'))
  }
}

onMounted(() => {
  initChart('position')
  fetchData('position')
  
  const chartWrapper = document.querySelector('.chart-wrapper')
  if(chartWrapper) {
    resizeObserver.observe(chartWrapper)
  }
})

onUnmounted(() => {
  if (positionChart) {
    positionChart.dispose()
  }
  if (applicationChart) {
    applicationChart.dispose()
  }
  if(salaryChart) {
    salaryChart.dispose()
  }
  resizeObserver.disconnect()
})

</script>

<style scoped>
.report-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.main-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
}

.button-group {
  display: flex;
  gap: 15px;
}

.el-button-group .el-button {
  transition: all 0.3s ease;
}

.el-button-group .el-button:not(.is-disabled):hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--success:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.excel-buttons {
  display: flex;
  gap: 10px;
}

.chart-wrapper {
  position: relative;
  width: 100%;
  height: 600px; /* 增加图表容器高度 */
  overflow: hidden;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>